const express = require('express');

const app = express();
const fs = require('fs');
//获取客户端 ip 地址
function getClientIp(req) {
    return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
    req.connection.remoteAddress || // 判断 connection 的远程 IP
    req.socket.remoteAddress || // 判断后端的 socket 的 IP
    req.connection.socket.remoteAddress;
}
app.use(function(request, response, next){
    response.setHeader('Access-Control-Allow-Origin', "*");
    response.setHeader('Access-Control-Allow-Headers', "*");
    fs.writeFileSync('./access.log', getClientIp(request) + '---' +decodeURI(request.url) + '\r\n', {flag: 'a'});
    next();
});

app.all('/server', (request, response) => {
    response.send('HELLO abc');
});

app.all('/json-server', (request, response) => {
    //响应结果 JSON 格式的响应体
    let data = {
        errno: 1,
        errmsg: '此用户名已经存在'
    };
    //将 js 对象转化为 JSON 字符串
    let json = JSON.stringify(data);
    //设置响应头 类型与字符集
    response.setHeader('Content-Type','application/json; charset=utf-8');
    //响应结果
    response.end(json);

});

app.listen(80, () => {
    console.log('服务已经启动....');
})
